#!/bin/bash

# Redis-rs2 集群停止脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${CYAN}🛑 Redis-rs2 集群停止脚本${NC}"
echo -e "${CYAN}============================${NC}"
echo

# 定义节点信息
declare -a NODES=("node1" "node2" "node3" "node4" "node5" "node6" "node7")
declare -a PORTS=("7001" "7002" "7003" "7004" "7005" "7006" "7007")

stopped_count=0
failed_count=0

echo -e "${BLUE}🔍 检查当前运行的节点...${NC}"

# 先尝试通过PID文件优雅停止
echo -e "${YELLOW}🔄 尝试优雅停止节点...${NC}"

for i in "${!NODES[@]}"; do
    node="${NODES[$i]}"
    port="${PORTS[$i]}"
    pidfile="logs/cluster/${node}.pid"
    
    if [ -f "$pidfile" ]; then
        pid=$(cat "$pidfile")
        if ps -p $pid > /dev/null 2>&1; then
            echo -e "${PURPLE}停止 ${node} (PID: ${pid})${NC}"
            
            # 发送SIGTERM信号进行优雅停止
            if kill -TERM $pid 2>/dev/null; then
                # 等待进程结束
                local timeout=10
                while [ $timeout -gt 0 ] && ps -p $pid > /dev/null 2>&1; do
                    sleep 1
                    timeout=$((timeout - 1))
                done
                
                if ps -p $pid > /dev/null 2>&1; then
                    echo -e "${YELLOW}  ⚠️  ${node} 未响应SIGTERM，使用SIGKILL${NC}"
                    kill -KILL $pid 2>/dev/null || true
                fi
                
                echo -e "${GREEN}  ✅ ${node} 已停止${NC}"
                stopped_count=$((stopped_count + 1))
            else
                echo -e "${RED}  ❌ 无法停止 ${node}${NC}"
                failed_count=$((failed_count + 1))
            fi
        else
            echo -e "${YELLOW}  ⚠️  ${node} PID文件存在但进程不运行${NC}"
        fi
        
        # 删除PID文件
        rm -f "$pidfile"
    else
        echo -e "${YELLOW}  ⚠️  ${node} PID文件不存在${NC}"
    fi
done

echo

# 通过端口强制停止残留进程
echo -e "${YELLOW}🔍 检查端口占用情况...${NC}"

for i in "${!PORTS[@]}"; do
    port="${PORTS[$i]}"
    node="${NODES[$i]}"
    
    if lsof -i :${port} >/dev/null 2>&1; then
        echo -e "${YELLOW}  ⚠️  端口 ${port} (${node}) 仍被占用，强制停止...${NC}"
        
        # 获取占用端口的进程并终止
        pids=$(lsof -ti :${port} 2>/dev/null || true)
        if [ ! -z "$pids" ]; then
            for pid in $pids; do
                echo -e "${PURPLE}    终止进程 ${pid}${NC}"
                kill -KILL $pid 2>/dev/null || true
            done
            stopped_count=$((stopped_count + 1))
        fi
    else
        echo -e "${GREEN}  ✅ 端口 ${port} (${node}) 已释放${NC}"
    fi
done

echo

# 清理资源
echo -e "${BLUE}🧹 清理资源...${NC}"

# 清理临时文件
if [ -d "logs/cluster" ]; then
    echo -e "${PURPLE}  清理日志文件...${NC}"
    # 保留日志文件但压缩旧的
    find logs/cluster -name "*.log" -mtime +7 -exec gzip {} \; 2>/dev/null || true
    echo -e "${GREEN}    ✅ 旧日志文件已压缩${NC}"
fi

# 清理PID文件
echo -e "${PURPLE}  清理PID文件...${NC}"
rm -f logs/cluster/*.pid 2>/dev/null || true
echo -e "${GREEN}    ✅ PID文件已清理${NC}"

# 检查是否有Redis相关的僵尸进程
echo -e "${PURPLE}  检查僵尸进程...${NC}"
zombie_processes=$(ps aux | grep cluster_redis_server | grep -v grep | wc -l)
if [ $zombie_processes -gt 0 ]; then
    echo -e "${YELLOW}    ⚠️  发现 ${zombie_processes} 个相关进程${NC}"
    ps aux | grep cluster_redis_server | grep -v grep | awk '{print $2}' | xargs kill -KILL 2>/dev/null || true
    echo -e "${GREEN}    ✅ 僵尸进程已清理${NC}"
else
    echo -e "${GREEN}    ✅ 没有发现僵尸进程${NC}"
fi

echo

# 最终状态检查
echo -e "${BLUE}📊 最终状态检查：${NC}"

all_stopped=true
for port in "${PORTS[@]}"; do
    if nc -z 127.0.0.1 $port 2>/dev/null; then
        echo -e "${RED}  ❌ 端口 ${port} 仍在监听${NC}"
        all_stopped=false
    fi
done

if [ "$all_stopped" = true ]; then
    echo -e "${GREEN}  ✅ 所有端口已释放${NC}"
fi

echo

# 结果总结
echo -e "${CYAN}📋 停止结果总结：${NC}"
echo -e "   🛑 成功停止: ${GREEN}${stopped_count}${NC} 个节点"
if [ $failed_count -gt 0 ]; then
    echo -e "   ❌ 停止失败: ${RED}${failed_count}${NC} 个节点"
fi

if [ "$all_stopped" = true ]; then
    echo -e "${GREEN}🎉 集群已完全停止！${NC}"
else
    echo -e "${YELLOW}⚠️  部分节点可能仍在运行，请检查${NC}"
fi

echo
echo -e "${CYAN}📝 有用的命令：${NC}"
echo -e "   🚀 重新启动集群: ${BLUE}./scripts/start_cluster.sh${NC}"
echo -e "   📊 检查集群状态: ${BLUE}./scripts/cluster_status.sh${NC}"
echo -e "   📋 查看日志: ${BLUE}ls -la logs/cluster/${NC}"
echo -e "   🗑️  清理所有日志: ${BLUE}rm -rf logs/cluster/*.log${NC}"

echo
echo -e "${GREEN}✨ 集群停止脚本执行完成！${NC}"